package whisper.api.gateway.frame.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import whisper.api.gateway.frame.auth.filter.permission.LightSwordUserDetailService;

/**
 * Created by JT on 2017/9/20.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LightSwordUserDetailService lightSwordUserDetailService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/health")
                .antMatchers("/monitor/**")
                .antMatchers("/forecast/**")
                .antMatchers("/observation/**")
                .antMatchers("/datacompare/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

        http.authorizeRequests()
                .antMatchers("/").permitAll()
//                .antMatchers("/health"
//                 ).permitAll() //默认不拦截静态资源的url pattern （2）
                .anyRequest().authenticated().and()
//                .httpBasic().disable()
                .formLogin()//.loginPage("/login")// 登录url请求路径 (3)
                .defaultSuccessUrl("/user").permitAll().and() // 登录成功跳转路径url(4)
                .logout().permitAll();



        http.logout().logoutSuccessUrl("/login"); // 退出默认跳转页面 (5)
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("root")
//                .password("root")
//                .roles("USER")
//                .and()
//                .withUser("admin")
//                .password("admin")
//                .roles("ADMIN");

        auth.userDetailsService(userDetailsService());
    }

    @Override
    public UserDetailsService userDetailsService()   {
        return lightSwordUserDetailService;
    }

}
